package com.grgbanking.it.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.grgbanking.it.system.entity.User;

/**
 * 登录过滤器,禁止未登录用户直接返回
 * @author pgwei
 *
 */
public class SessionFilter implements Filter {

	static final String LOGOUT_PAGE = "/logout.jsp";

	// static final String ERROR_PAGE = "/publicCtrl/error.jsp" ;

	static String[] NO_FILTER_PATH = null;

	public SessionFilter() {
		super();
	}

	public void init(FilterConfig fc) throws ServletException {

	}

	/**
	 * 过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String param = req.getQueryString() == null ? "" : req.getQueryString();
		String uri = req.getRequestURI();
		String context_path = req.getContextPath();
		if (param != null) {
		}

		if (!(uri.indexOf("log") > -1) && !(uri.equals("/"))
				&& !(param.indexOf("log") > -1)
				&& !(param.indexOf("getCheckCode") > -1)
				&& !(uri.indexOf("md5_2.1.js") > -1)
				&& !(uri.indexOf("login.js") > -1)
				&& !(uri.indexOf("ext-all") > -1)
				&& !(uri.indexOf("ext-base") > -1)
				&& !(uri.indexOf("/services/") > -1)
				&& !(uri.indexOf("/down/") > -1)
				&& !(uri.indexOf("/wx/") > -1) 
				&& !(uri.indexOf("/operationWork/oa") > -1) ) {
			HttpSession session = req.getSession(false);
			User sysUser = session == null ? null : (User) session
					.getAttribute("loginUser");
			if (sysUser == null) {
				HttpServletResponse resp = (HttpServletResponse) response;

				if (req.getHeader("X-Requested-With") != null) { // Ajax请求
					resp.setContentType("text/json;charset=UTF-8");
					resp.getWriter().print("{success:false,info:'timeout'}");
					return;
				} else {
					resp.sendRedirect(context_path + LOGOUT_PAGE
							+ "?timeout=true");
					return;
				}
			}
		}
		filterChain.doFilter(request, response);
	}

	public void destroy() {
	}
}
